import Vue from 'vue'
import Vuex from 'vuex'
import { loginApI } from '../api/login'
import storage from '../utils/storage'
Vue.use(Vuex)

const store = new Vuex.Store({
  // 开启严格模式 一切数据的修改都要在 mutations 中进行
  strict: true,
  state: {
    // 登录
    token: storage.get('token') || '',
    refreshToken: storage.get('refresh_token') || '',
    userInfo: {
      name: '',
      photo: storage.get('photo')
    }
  },
  mutations: {
    setToken (state, tokenStr) {
      state.token = tokenStr
      storage.set('token', tokenStr)
    },
    setRefreshToken (state, refreshTokenStr) {
      state.refreshToken = refreshTokenStr
      storage.set('refresh_token', refreshTokenStr)
    },
    setUserInfo (state, userObj) {
      state.userInfo = userObj
    },
    setUserName (state, val) {
      state.userInfo.name = val
    },
    setUserPhoto (state, val) {
      state.userInfo.photo = val
      storage.set('photo', val)
    }
  },
  actions: {
    async asyncLoginAction (store, formLogin) {
      // 1.发送登录请求
      const resp = await loginApI(formLogin)
      const { token, refresh_token: refreshToken } = resp.data
      // 2.提交到 mutation - 同步 token 和 refreshToken
      store.commit('setToken', token)
      store.commit('setRefreshToken', refreshToken)
    }
  },
  modules: {
  }
})
export default store
